<template>
  <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">
    <!-- 主要内容 -->
    <el-main>
      <el-header>
        <el-col :span="6">
          <span>项目编号：{{ formData.projectCode }}</span>
        </el-col>
        <el-col :span="6">
          <span>项目名称：{{ formData.projectName  }}</span>
        </el-col>
        <el-col :span="6">
          <span v-if="formData.purchaseCategoryId === '1'">采购类别：货物类</span>
          <span v-else-if="formData.purchaseCategoryId === '2'">采购类别：服务类</span>
          <span v-else-if="formData.purchaseCategoryId === '3'">采购类别：工程类</span>
          <span v-else>采购类别：其他采购类别</span>
        </el-col>
        <el-col :span="6">
          <span>预算金额：{{ formData.budget }}元</span>
        </el-col>
      </el-header>

      <!-- "一键归档" button -->
      <el-button type="primary" @click="archiveFiles" :disabled="archiveSubmitStatus === '已提交'">一键归档</el-button>
      <el-dialog v-model="failureDialogVisible" title="归档失败" @close="failureDialogVisible = false">
        归档失败，请重试。
      </el-dialog>

      <!-- 归档文件 table -->
      <br><br><span>归档文件：</span>
      <el-table :data="projectTable" style="width: 100%" class="table" border v-loading="loading">
        <el-table-column prop="fileCategory" label="文件类别" width="150px"></el-table-column>
        <el-table-column prop="fileName" label="文件名" width="300px"></el-table-column>
        <el-table-column prop="supplierName" label="潜在供应商" width="150px"></el-table-column>
        <el-table-column prop="fileArchiveTime" label="归档时间" width="200px"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button  @click="handleRowClick(scope.row)" :disabled="archiveSubmitStatus === '已提交'" v-if="scope.row.fileCategory === '采购邀请函'" style="margin-left: 10px;display: inline">补传</el-button>
            <el-upload style="margin-left: 10px;display: inline"
                       :show-file-list="false"
                       :before-upload = "beforeUploadFile"
                       :headers='token'
                       :action="uploadUrl"
                       ref="upload"
                       accept=".pdf"
                       :on-success="handleSuccess"
                       :on-progress="progress"
                       :on-error="fileError"
                       v-loading.fullscreen.lock="loading"
                       :element-loading-text="progressPercentTitle"
                       element-loading-spinner="el-icon-loading"
                       element-loading-backgroud="rgba(0,0,0,0.1)"
            >

              <el-button  @click="uploadFile(scope.row)" :disabled="archiveSubmitStatus === '已提交' || scope.row.fileCategory === '成交供应商报价'" v-if="scope.row.fileCategory !== '采购邀请函'" style="margin-right: 10px">补传</el-button>
              </el-upload>

            <el-button style="margin-left: 20px" @click="downloadFile(scope.row.filePath,scope.row.fileCategory,scope.row.fileName)"  v-if="scope.row.fileName !== '未上传文件'">下载</el-button>
            <el-button @click="deleteArchiveManage(scope.row.filePath,scope.row.fileCategory,scope.row.fileName)" style="margin-left: 30px" :disabled="archiveSubmitStatus === '已提交' || scope.row.fileCategory === '成交供应商报价'" v-if="scope.row.fileName !== '未上传文件'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <br><br><span>审批流程时间表：</span>
      <el-table :data="approveTable" style="width: 100%" class="table" border v-loading="loading">
        <el-table-column prop="nodeName" label="结点名称" ></el-table-column>
        <el-table-column prop="submitP" label="提交人" ></el-table-column>
        <el-table-column prop="submitTime" label="提交时间" ></el-table-column>
        <el-table-column prop="approvalP" label="审批人" ></el-table-column>
        <el-table-column prop="approvalTime" label="审批时间" ></el-table-column>
        <el-table-column prop="approvalResult" label="审批结果" ></el-table-column>
      </el-table>

          <!-- "打包下载" (Pack & Download) button -->
      <el-button class="packDownload" type="primary" @click="packAndDownload">打包下载</el-button>&emsp;<span>（打包成一个压缩包）</span>
      <div style="margin-top: 20px">
        <el-col :span="11">
          <span>提交状态：{{ archiveSubmitStatus }}</span>
        </el-col>
        <el-col :span="11">
          <span>提交时间：{{ formData.archiveSubmitTime }}</span>
        </el-col>
        <el-col :span="11">
          <span >审批状态：{{ formData.archiveApproveStatus }}</span>
        </el-col>
        <el-col :span="11">
          <span>审批时间：{{ formData.archiveApproveTime }}</span>
        </el-col>
      </div>
      <!-- 提交按钮 -->
      <div style="margin-left: 220px;margin-top: 40px;">
        <span>
        <el-button
            class="submit-button"
            type="primary"
            @click="submitForArchive"
            :disabled="archiveSubmitStatus === '已提交'"
        >
          提交审批
        </el-button>
        </span>
        <span style="margin-left: 40px;">
        <el-button  @click="goBack" type="primary">返回</el-button>
        </span>
      </div>
    </el-main>

    <el-dialog title="补传文件" :visible.sync="uploadDialogVisible">
      <span>文件类别：{{ selectedFileCategory }}</span>
      <hr>
      <span>请选择供应商：</span>
      <el-select v-model="selectedSupplier" placeholder="选择供应商" style="margin-left: 1%">
        <el-option
            v-for="(name, index) in supplierName"
            :key="index"
            :label="name"
            :value="name"
        ></el-option>
      </el-select>
      <el-upload style="margin-left: 10px;display: inline"
                 :show-file-list="false"
                 :before-upload = "beforeUploadFile"
                 :headers='token'
                 :action="uploadUrl"
                 ref="upload"
                 accept=".pdf"
                 :on-success="handleSuccess"
                 :on-progress="progress"
                 :on-error="fileError"
                 v-loading.fullscreen.lock="loading"
                 :element-loading-text="progressPercentTitle"
                 element-loading-spinner="el-icon-loading"
                 element-loading-backgroud="rgba(0,0,0,0.1)"
      >

        <el-button @click="uploadFile" :disabled="archiveSubmitStatus === '已提交'" style="margin-left: 5%">上传</el-button>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
//npm install jszip file-saver  引入jszip
import {
  archive,
  deleteArchive,
  downloadZip,
  selectAllApproveTable,
  selectAllArchiveManger,
  submitArchive
} from "@/api/archive/archive.js";
import request from "@/utils/request";
import {serverIp} from "../../../public/config";


export default {

  created() {
    // 接收路由传递的数据
    this.formData.projectCode = this.$route.params.projectCode;
    this.formData.projectName = this.$route.params.projectName;
    this.formData.purchaseCategoryId = this.$route.params.purchaseCategoryId;
    this.formData.budget = this.$route.params.budget;
    this.formData.archiveSubmitTime = this.$route.params.archiveSubmitTime;
    this.formData.archiveApproveStatus = this.$route.params.archiveApproveStatus;
    this.formData.archiveApproveTime = this.$route.params.archiveApproveTime;
    this.formData.quaSubmitP = this.$route.params.quaSubmitP;
    this.formData.projectId = this.$route.params.projectId;
    //this.uploadUrl = `${serverIp}/archive/uploadfile?projectId=${this.formData.projectId}&fileCategory=${this.projectTable.fileCategory}&supplierName=${this.selectedSupplier}`;

  },

  mounted() {
    this.selectAllProjectTable()
    this.selectApproveTable()
  },


  data() {
    return {
      //保存传递过来的数据
      formData: {
        projectCode: '',
        projectName: '',
        purchaseCategoryId: '',
        budget: '',
        archiveSubmitTime:'',
        archiveApproveStatus:'',
        archiveApproveTime:'',
        projectId:'',
        supplierName:'',
        quaSubmitP:'',
      },

      projectTable: [],
      approveTable:[],

      archiveSubmitStatus:'',
      //保存传来的供应商数组
      supplierName:[],
      // 已将上传的潜在供应商
      hasUploadSupplierName:[],
      //下拉选择框选定的值
      selectedSupplier: '',
      selectedFileCategory:'',

      //上传的地址
      token: { Authorization:localStorage.getItem("token") },
      uploadUrl: ``,
      progressPercentTitle: "", // 展示百分比
      progressPercent: 0, // 进度
      loading: true,

      theData: [], // 新添加的属性
      failureDialogVisible: false,

      uploadDialogVisible: false, // 控制上传对话框的显示

    };
  },


  methods: {

    //初始化projectTable里的数据
    async selectAllProjectTable() {

      let data ={ projectId: this.formData.projectId };
      try {
        const response = await selectAllArchiveManger(data);
        if (response){
          this.loading = false
        }
        if (response.data.code === 200) {
          this.supplierName = response.data.data.supplierName;
          // 判断是否所有文件的 fileName 都等于 "未上传"
          const allFilesAreUnuploaded = response.data.data.archiveFileList.every(
              (file) => file.fileName === '未上传'
          );

          if (!allFilesAreUnuploaded) {
            this.projectTable = response.data.data.archiveFileList;
          }
          this.archiveSubmitStatus = response.data.data.archiveSubmitStatus;
        } else if(response.data.code === 10000){
          this.$message({
            type: 'info',
            message: '当前操作使数据自动同步，请再次执行!'
          });
          await this.selectAllProjectTable();
        } else{
          this.projectTable = [];
          this.total = 0;
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error('Error fetching supplier data:', error);
      }
    },

    async selectApproveTable() {
      let data ={ projectId: this.formData.projectId };
      try {
        const response = await selectAllApproveTable(data);
        this.approveTable = response.data.data.statusList;
      } catch (error) {
        console.error('Error fetching supplier data:', error);
      }
    },

    // 一键归档按钮
    async archiveFiles() {
      this.$message.info('正在归档中......');
      let data ={ projectId: this.formData.projectId };
      try {
        const response = await archive(data);
        if (response){
          this.loading = false
        }
        if (response.data.code === 200) {
          this.$message.success('一键归档成功！');
          await this.selectAllProjectTable()
        }else{
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error('Error fetching supplier data:', error);
      }
      if (this.archiveSubmitStatus === '已提交') {
        this.$message({
          type: 'info',
          message: '已提交审批，无法执行一键归档。'
        });
      }
    },

    beforeUploadFile(file) {

      console.log("before upload");

      console.log(file);

      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);

      if (extension !== "pdf") {

        this.$message.warning("只能上传后缀是.pdf");

        return false;

      }

    },


    //删除
    async deleteArchiveManage(filePath,fileCategory,fileName) {
      try {
        this.$confirm('确认删除吗吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = {projectId: this.formData.projectId,filePath:filePath,fileCategory:fileCategory,fileName:fileName}
          let response = await deleteArchive(data);
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            await this.selectAllProjectTable();
          } else if (response.data.code === 10000){
            this.$message({
              type: 'info',
              message: '当前操作使数据自动同步，请再次执行!'
            });
            await this.selectAllProjectTable();
          } else {
            this.$message.error(response.data.msg);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除。'
          });
        })
      } catch (error) {
        console.error('Error during archive deletion:', error);
        this.$message.error("删除失败");
      }
    },

    // 补传按钮点击事件处理
    handleRowClick(row) {
        // 如果文件类别为'采购邀请函'，则显示上传对话框
        this.uploadDialogVisible = true;
        this.selectedFileCategory = row.fileCategory;
    },
    //补传
    uploadFile(row) {
      const fileCategory = row.fileCategory || this.selectedFileCategory;
      const selectedSupplier = this.selectedSupplier;
      // 更新uploadUrl
      this.uploadUrl = `${serverIp}/archive/uploadfile?projectId=${this.formData.projectId}&fileCategory=${fileCategory}&supplierName=${selectedSupplier}`;
    console.log(this.formData.projectId + "===========" + fileCategory + "===========" +selectedSupplier)
      },

    // 上传文件时钩子
    progress(event,file,fileList){
      this.loading = true;
      this.progressPercent = Math.floor(event.percent);
      this.progressPercentTitle = "已上传" + this.progressPercent + "%"
    },
    fileError(){
      this.loading=false;
      this.$message.error("失败")
      this.uploadDialogVisible = false;
    },
    handleSuccess(){
      this.loading = false;
      alert("上传成功！")
      this.selectAllProjectTable()
      this.uploadDialogVisible = false;
    },

    //下载
    async downloadFile(filePath,fileCategory,fileName){
      if (!filePath) {
        this.$message.error("文件路径不存在，无法下载。");
        return;
      }
      let data={
        'projectId':this.formData.projectId,
        'filePath':filePath,
        'fileCategory':fileCategory,
        'fileName':fileName
      }
      let res=await request(
          {
            url: "/archive/downloadfile",
            method: "post",
            responseType: 'blob',
            data:data,
            timeout:150000
          }
      )
      if(res.headers['content-type']!=='application/octet-stream'){
        this.$message({
          message:'数据已发生变化，请重试'
        })
        return;
      }
      let blob = new Blob([res.data], {type: 'application/octet-stream'})
      // 创建一个临时的URL，用于下载文件
      let url = window.URL.createObjectURL(blob)
      // 创建一个a标签，指定下载链接和文件名
      let link = document.createElement('a')
      link.href = url
      link.download =filePath // 这里可以根据实际情况指定文件名和扩展名
      // 触发a标签的点击事件，开始下载文件
      link.click()
      // 释放URL资源
      window.URL.revokeObjectURL(url)
    },

    //打包下载
     async packAndDownload() {
        let theData ={ projectId: this.formData.projectId }
        console.log("=========theData===========" + JSON.stringify(theData))
        try {
          this.$message({
            type: 'info',
            message: '正在打包下载中...'
          });
          let response = await downloadZip(theData);
          if(response.headers['content-type']!=='application/octet-stream'){
            this.$message({
              message:'数据已发生变化，请重试'
            })
            return;
          }
          // 问题，response.data为空，new blob对象为空
          let blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
          // 创建一个临时的URL，用于下载文件
          let url = window.URL.createObjectURL(blob)
          // 创建一个a标签，指定下载链接和文件名
          let link = document.createElement('a')
          link.href = url
          link.download ="归档文件.zip" // 这里可以根据实际情况指定文件名和扩展名
          // 触发a标签的点击事件，开始下载文件
          link.click()
          // 释放URL资源
          window.URL.revokeObjectURL(url)
        } catch (error) {
          this.$message.error("存在文件路径为空，下载失败");
        }
     },

    //提交审批
    async submitForArchive() {
      if (this.archiveSubmitStatus === '已提交') {
        this.$message({
          type: 'info',
          message: '已提交审批，不能再次提交'
        });
        return;
      }
        // 发出事件以更新index中的审批状态
        this.$confirm('确认提交审批吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let data = {projectId: this.formData.projectId,quaSubmitP:this.formData.quaSubmitP}
          let res = await submitArchive(data)
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.archiveSubmitStatus = "已提交"
            await this.selectAllProjectTable();
            await this.selectApproveTable();
            const currentDate = new Date();
            this.formData.archiveSubmitTime = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')} ${currentDate.getHours().toString().padStart(2, '0')}:${currentDate.getMinutes().toString().padStart(2, '0')}:${currentDate.getSeconds().toString().padStart(2, '0')}`;

          } else if (res.data.code === 10000){
            this.$message({
              type: 'info',
              message: '数据存在差异，已自动同步，请重新提交!'
            });
            await this.selectAllProjectTable();
          }else if (res.data.code === 114514){
              this.$message({
                type: 'error',
                message: res.data.msg,
              });
            await this.selectAllProjectTable();
            await this.selectApproveTable();
            const currentDate = new Date();
            this.formData.archiveSubmitTime = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')} ${currentDate.getHours().toString().padStart(2, '0')}:${currentDate.getMinutes().toString().padStart(2, '0')}:${currentDate.getSeconds().toString().padStart(2, '0')}`;

          }else {
            this.$message.error(res.data.msg)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '提交审批失败，请重试。'
          });
        })
    },


    //返回archive
    goBack() {
      this.$router.push('archive');
    },

  },

};
</script>

<style>
.table{
  margin-top: 10px;
}
.packDownload{
  margin-top: 30px;
}
.submit-button {
  margin-top: 20px;
  margin-right: 20px;
}

</style>

